﻿using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Runtime.Serialization.Formatters.Binary;

namespace WorkNodeFramework
{
    public class StringParser
    {
        public static T Parse<T>(string content, T defaultValue) {
            Type type = typeof(T);
            if (type == typeof(string))
                return (T)((object)content);
            if (IsConvertibleType(type))
                return (T)Convert.ChangeType(content, type);
            TypeConverter converter = TypeDescriptor.GetConverter(type);
            if ((converter != null) && converter.CanConvertFrom(typeof(string)))
                return (T)converter.ConvertTo(content, type);
            if (type.IsEnum)
                return (T)Enum.Parse(type, content);
            if (type.IsSerializable)
                return (T)SerializationService.Deserialize(content);
            return defaultValue;
        }

        public static string ConvertToString(object obj) {
            if (obj is string)
                return (string)obj;
            Type type = obj.GetType();
            if (IsConvertibleType(type))
                return obj.ToString();
            if (type.IsSerializable)
                return SerializationService.SerializeToBase64String(obj);
            return obj.ToString();
        }

        static bool IsConvertibleType(Type type) { 
            if(type.IsPrimitive)
                return true;
            if(type == typeof(System.DateTime)||
                type == typeof(System.Decimal))
                return true;
            return false;
        }
    }
}
